package cn.itrip.auth.controller;

import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@Controller
@RequestMapping(value = "/api")
public class TokenController {
    @Resource
    private TokenService tokenService;

    @RequestMapping(value = "/validateToken", method = RequestMethod.GET,produces= "application/json",headers = "token")
    @ResponseBody
    public Dto validate(HttpServletRequest request) {

        try {
            boolean result = tokenService.validate(request.getHeader("user-agent"),request.getHeader("token"));
            if (result){
                return DtoUtil.returnSuccess("token有效");
            } else {
                return DtoUtil.returnSuccess("token无效");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_UNKNOWN);
        }

    }

    @RequestMapping(value = "/retoken", method = RequestMethod.POST,produces= "application/json",headers = "token")
    @ResponseBody
    public Dto reloadToken(HttpServletRequest request) {
        String oldToken = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        try {
            String token = tokenService.reloadToken(agent,oldToken);
            //返回ItripTokenVO
            ItripTokenVO tokenVO=new ItripTokenVO(token,
                    Calendar.getInstance().getTimeInMillis()+TokenService.SESSION_TIMEOUT*1000,//2h有效期
                    Calendar.getInstance().getTimeInMillis());

            return DtoUtil.returnDataSuccess(tokenVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_REPLACEMENT_FAILED);
        }
    }
}
